package cn.jingyuan.swan.example.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/*
    如果 ServerSocketChannel 以非阻塞模式被调用，
    当没有传入连接在等待时，ServerSocketChannel.accept( )会立即返回 null。
    正是这种检查连接而不阻塞的能力实现了可伸缩性并降低了复杂性。可选择性也因此得到实现。
    我们可以使用一个选择器实例来注册一个 ServerSocketChannel 对象以实现新连接到达时自动通知的功能。
    以下代码演示了如何使用一个非阻塞的 accept( ) 方法：
 */
public class ChannelAccept {

    public static void main(String[] args) throws IOException {

        int port = 9090;

        ServerSocketChannel serverChannel = ServerSocketChannel.open();

        serverChannel.configureBlocking(false);

        serverChannel.bind(new InetSocketAddress(port));

        while (true) {
            SocketChannel clientChannel = serverChannel.accept();
            if (null == clientChannel) {
                continue;
            }

            InetSocketAddress address = (InetSocketAddress) clientChannel.getRemoteAddress();

            String hostAddress = address.getAddress().getHostAddress();
            int addressPort = address.getPort();

            System.out.println("Incoming connection from: " + hostAddress + ":" + addressPort);

            ByteBuffer buffer = ByteBuffer.wrap("hello".getBytes(StandardCharsets.UTF_8));
            buffer.rewind();

            clientChannel.write(buffer);
            clientChannel.close();
        }
    }

}
